package com.uzai.console.service.cms.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.ciku.CikuKeywordsReplyIdListDto;
import com.uzai.console.dto.cms.activity.*;
import com.uzai.console.dto.cms.tbgoods.CmsTbGoodsQuery;
import com.uzai.console.entity.CmsActivity;
import com.uzai.console.entity.CmsActivityDetail;
import com.uzai.console.entity.CmsMerTbGoods;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.jsonvo.merbaseconfig.CmsHomePageConfigJson;
import com.uzai.console.mapper.CmsActivityDetailMapper;
import com.uzai.console.mapper.CmsActivityMapper;
import com.uzai.console.mapper.CmsMerTbGoodsMapper;
import com.uzai.console.mapper.MerBaseConfigMapper;
import com.uzai.console.service.alipaydetail.impl.AlipayDetailServiceImpl;
import com.uzai.console.service.cms.CmsActivityService;
import com.uzai.console.service.cms.CmsTbGoodsService;
import com.uzai.console.service.qiniu.QiniuService;
import com.uzai.console.service.tencent.TencentCosService;
import com.uzai.console.vo.cms.activity.CmsActivityDetailInfoVo;
import com.uzai.console.vo.cms.activity.CmsActivityInfoVo;
import com.uzai.console.vo.cms.homepage.CmsHomePageUploadQrcodeVo;
import com.uzai.console.vo.cms.tbgoods.CmsMerTbGoodsInfoVo;
import com.uzai.console.vo.cms.tbgoods.CmsTbGoodsInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class CmsActivityServiceImpl implements CmsActivityService {

    Logger logger = LoggerFactory.getLogger(CmsActivityServiceImpl.class);

    @Autowired
    private CmsActivityMapper cmsActivityMapper;
    @Autowired
    private CmsActivityDetailMapper cmsActivityDetailMapper;
    @Autowired
    private CmsMerTbGoodsMapper cmsMerTbGoodsMapper;
    @Autowired
    private CmsTbGoodsService cmsTbGoodsService;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询CMS活动列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return CmsActivityInfoVo
     */
    public Page<CmsActivityInfoVo> findCmsActivityList(CmsActivityQuery cmsActivityQuery){
        //新建返回到页面的LIST对象
        List<CmsActivityInfoVo> cmsActivityInfoVoList = new ArrayList<>();
        //返回到页面分页对象
        Page<CmsActivityInfoVo> pageVo = new Page<>();

        //执行分页查询对象
        Page<CmsActivity> page = new Page<>();
        cmsActivityQuery.convert(page);
        List<CmsActivity> cmsActivityList = cmsActivityMapper.findByList(page, cmsActivityQuery);

        int now = DateUtil.getNowTime();

        if(cmsActivityList != null){
            for (CmsActivity cmsActivity : cmsActivityList){
                CmsActivityInfoVo cmsActivityInfoVo = new CmsActivityInfoVo();
                BeanUtils.copyProperties(cmsActivity, cmsActivityInfoVo);

                //位置keyList
                if(StringUtils.isNotBlank(cmsActivity.getLocation())){
                    cmsActivityInfoVo.setLocationList(JSONObject.parseArray(cmsActivity.getLocation(), String.class));
                }

                //商品id列表
                if(StringUtils.isNotBlank(cmsActivity.getItemId())){
                    List<String> itemIdList = JSONObject.parseArray(cmsActivity.getItemId(), String.class);
                    cmsActivityInfoVo.setItemIdList(itemIdList);
                }

                //卡片回复关键字列表
                cmsActivityInfoVo.setCardKeywordList(JSONObject.parseArray(cmsActivity.getCardKeywords(), String.class));

                //状态
                if(cmsActivity.getStatus() == 1){ //正常情况下，状态可分为（未开始；进行中；已结束）
                    if(Tools.getInteger(cmsActivity.getStartTime()).intValue() > now){
                        cmsActivityInfoVo.setStatusName("未开始");
                    } else {
                        if(Tools.getInteger(cmsActivity.getEndTime()).intValue() > now){
                            cmsActivityInfoVo.setStatusName("进行中");
                        }else{
                            cmsActivityInfoVo.setStatusName("已结束");
                        }
                    }
                }else{
                    cmsActivityInfoVo.setStatusName("暂停");
                }

                //位置明细
                CmsActivityDetailQuery  cmsActivityDetailQuery = new CmsActivityDetailQuery();
                cmsActivityDetailQuery.setMerId(cmsActivityQuery.getMerId());
                cmsActivityDetailQuery.setActivityId(cmsActivityInfoVo.getId());
                List<CmsActivityDetail> cmsActivityDetailList = cmsActivityDetailMapper.findByList(cmsActivityDetailQuery);
                if(cmsActivityDetailList != null){
                    List<CmsActivityDetailInfoVo> cmsActivityDetailInfoVoList = new ArrayList<>();
                    for (CmsActivityDetail cmsActivityDetail : cmsActivityDetailList){
                        CmsActivityDetailInfoVo cmsActivityDetailInfoVo = new CmsActivityDetailInfoVo();
                        BeanUtils.copyProperties(cmsActivityDetail, cmsActivityDetailInfoVo);
                        cmsActivityDetailInfoVoList.add(cmsActivityDetailInfoVo);
                    }
                    cmsActivityInfoVo.setCmsActivityDetailInfoVoList(cmsActivityDetailInfoVoList);
                }
                cmsActivityInfoVoList.add(cmsActivityInfoVo);
            }
        }
        BeanUtils.copyProperties(page, pageVo);

        pageVo.setRecords(cmsActivityInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询CMS活动详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public CmsActivityInfoVo findCmsActivityInfo(CmsActivityIdDto cmsActivityIdDto){

        if(cmsActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        CmsActivity cmsActivity = cmsActivityMapper.selectById(cmsActivityIdDto.getId(), cmsActivityIdDto.getMerId());
        if(cmsActivity == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该活动不存在");
        }

        CmsActivityInfoVo cmsActivityInfoVo = new CmsActivityInfoVo();
        BeanUtils.copyProperties(cmsActivity, cmsActivityInfoVo);

        //位置keyList
        if(StringUtils.isNotBlank(cmsActivity.getLocation())){
            cmsActivityInfoVo.setLocationList(JSONObject.parseArray(cmsActivity.getLocation(), String.class));
        }

        //商品id列表
        if(StringUtils.isNotBlank(cmsActivity.getItemId())){
            List<String> itemIdList = JSONObject.parseArray(cmsActivity.getItemId(), String.class);
            cmsActivityInfoVo.setItemIdList(itemIdList);
        }

        //卡片回复关键字列表
        cmsActivityInfoVo.setCardKeywordList(JSONObject.parseArray(cmsActivity.getCardKeywords(), String.class));

        Integer now = DateUtil.getNowTime();
        //状态
        if(cmsActivity.getStatus() == 1){ //正常情况下，状态可分为（未开始；进行中；已结束）
            if(Tools.getInteger(cmsActivity.getStartTime()).intValue() > now){
                cmsActivityInfoVo.setStatusName("未开始");
            } else {
                if(Tools.getInteger(cmsActivity.getEndTime()).intValue() > now){
                    cmsActivityInfoVo.setStatusName("进行中");
                }else{
                    cmsActivityInfoVo.setStatusName("已结束");
                }
            }
        }else{
            cmsActivityInfoVo.setStatusName("暂停");
        }

        //位置明细
        CmsActivityDetailQuery  cmsActivityDetailQuery = new CmsActivityDetailQuery();
        cmsActivityDetailQuery.setMerId(cmsActivity.getMerId());
        cmsActivityDetailQuery.setActivityId(cmsActivityInfoVo.getId());
        List<CmsActivityDetail> cmsActivityDetailList = cmsActivityDetailMapper.findByList(cmsActivityDetailQuery);
        if(cmsActivityDetailList != null){
            List<CmsActivityDetailInfoVo> cmsActivityDetailInfoVoList = new ArrayList<>();
            for (CmsActivityDetail cmsActivityDetail : cmsActivityDetailList){
                CmsActivityDetailInfoVo cmsActivityDetailInfoVo = new CmsActivityDetailInfoVo();
                BeanUtils.copyProperties(cmsActivityDetail, cmsActivityDetailInfoVo);
                cmsActivityDetailInfoVoList.add(cmsActivityDetailInfoVo);
            }
            cmsActivityInfoVo.setCmsActivityDetailInfoVoList(cmsActivityDetailInfoVoList);
        }

        return cmsActivityInfoVo;
    }

    /**
     * 添加CMS活动详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param cmsActivityInfoDto
     * @return null
     */
    @Transactional
    public void addCmsActivity(CmsActivityInfoDto cmsActivityInfoDto){

        if(StringUtils.isBlank(cmsActivityInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动主标题");
        }

        if(cmsActivityInfoDto.getItemIdList() == null || cmsActivityInfoDto.getItemIdList().size() < 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择活动关联的商品信息");
        }

        CmsActivity cmsActivity = new CmsActivity();

        Integer now = DateUtil.getNowTime();

        cmsActivity.setId(IdWorker.getId());
        cmsActivity.setCreateTime(now);
        cmsActivity.setUpdateTime(now);

        cmsActivity.setMerId(cmsActivityInfoDto.getMerId());
        cmsActivity.setName(cmsActivityInfoDto.getName());
        cmsActivity.setSubName(cmsActivityInfoDto.getSubName());
        cmsActivity.setSource(1); //运营商自建活动
        cmsActivity.setType(cmsActivityInfoDto.getType());
        cmsActivity.setShowTitle(Tools.getInteger(cmsActivityInfoDto.getShowTitle()));
        cmsActivity.setShowTime(cmsActivityInfoDto.getShowTime());
        cmsActivity.setStartTime(cmsActivityInfoDto.getStartTime());
        cmsActivity.setEndTime(cmsActivityInfoDto.getEndTime());
        cmsActivity.setPageStyle(cmsActivityInfoDto.getPageStyle());
        //活动添加时，url后面自动带上活动id参数
        cmsActivity.setUrl(cmsActivityInfoDto.getUrl() + cmsActivity.getId());
        if(cmsActivityInfoDto.getLocationList() != null){
            cmsActivity.setLocation(Tools.getStrEmpty(JSONObject.toJSONString(cmsActivityInfoDto.getLocationList())));
        }
        cmsActivity.setStatus(1);  //默认为正常1
        cmsActivity.setItemId(Tools.getStrEmpty(JSONObject.toJSONString(cmsActivityInfoDto.getItemIdList())));

        cmsActivity.setCardReply(cmsActivityInfoDto.getCardReply());
        cmsActivity.setCardTitle(cmsActivityInfoDto.getCardTitle());
        cmsActivity.setCardContent(cmsActivityInfoDto.getCardContent());
        cmsActivity.setCardImg(cmsActivityInfoDto.getCardImg());
        //卡片回复关键字列表
        cmsActivity.setCardKeywords(Tools.getStrEmpty(JSONObject.toJSONString(cmsActivityInfoDto.getCardKeywordList())));


        //保存活动
        cmsActivityMapper.insertSelective(cmsActivity);

        //保存活动明细（展示位置）
        List<CmsActivityDetailInfoDto> cmsActivityDetailInfoDtoList = cmsActivityInfoDto.getCmsActivityDetailInfoDtoList();
        if(cmsActivityDetailInfoDtoList != null && cmsActivityDetailInfoDtoList.size() > 0){
            for (CmsActivityDetailInfoDto cmsActivityDetailInfoDto : cmsActivityDetailInfoDtoList) {
                CmsActivityDetail cmsActivityDetail = new CmsActivityDetail();
                cmsActivityDetail.setId(IdWorker.getId());
                cmsActivityDetail.setCreateTime(now);
                cmsActivityDetail.setUpdateTime(now);
                cmsActivityDetail.setMerId(cmsActivityInfoDto.getMerId());
                cmsActivityDetail.setActivityId(cmsActivity.getId());
                cmsActivityDetail.setLocation(cmsActivityDetailInfoDto.getLocation());
                String value = cmsActivityDetailInfoDto.getValue();
                if(StringUtils.isNotBlank(value)){
                    JSONObject jsonObjectValue = JSONObject.parseObject(value);
                    jsonObjectValue.put("id",cmsActivityDetail.getId() + "");
                    jsonObjectValue.put("url",cmsActivity.getUrl());
                    jsonObjectValue.put("activityId", cmsActivity.getId() + "");
                    jsonObjectValue.put("startTime", cmsActivity.getStartTime());
                    jsonObjectValue.put("endTime", cmsActivity.getEndTime());
                    cmsActivityDetail.setValue(Tools.getStrEmpty(JSONObject.toJSONString(jsonObjectValue)));
                }
                cmsActivityDetailMapper.insert(cmsActivityDetail);
            }
        }
    }

    /**
     * 修改CMS活动详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param cmsActivityInfoDto
     * @return null
     */
    @Transactional
    public void updateCmsActivity(CmsActivityInfoDto cmsActivityInfoDto){

        if(cmsActivityInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        if(StringUtils.isBlank(cmsActivityInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动主标题");
        }

        if(cmsActivityInfoDto.getItemIdList() == null || cmsActivityInfoDto.getItemIdList().size() < 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择活动关联的商品信息");
        }

        CmsActivity cmsActivity = cmsActivityMapper.selectById(cmsActivityInfoDto.getId(), cmsActivityInfoDto.getMerId());

        if(cmsActivity == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该活动不存在");
        }

        Integer now = DateUtil.getNowTime();
        cmsActivity.setUpdateTime(now);
        cmsActivity.setName(cmsActivityInfoDto.getName());
        cmsActivity.setSubName(cmsActivityInfoDto.getSubName());
        cmsActivity.setType(cmsActivityInfoDto.getType());
        cmsActivity.setShowTitle(Tools.getInteger(cmsActivityInfoDto.getShowTitle()));
        cmsActivity.setShowTime(cmsActivityInfoDto.getShowTime());
        cmsActivity.setStartTime(cmsActivityInfoDto.getStartTime());
        cmsActivity.setEndTime(cmsActivityInfoDto.getEndTime());
        cmsActivity.setPageStyle(cmsActivityInfoDto.getPageStyle());
        cmsActivity.setUrl(cmsActivityInfoDto.getUrl() + cmsActivity.getId());
        cmsActivity.setItemId(Tools.getStrEmpty(JSONObject.toJSONString(cmsActivityInfoDto.getItemIdList())));
        if(cmsActivityInfoDto.getLocationList() != null){
            cmsActivity.setLocation(Tools.getStrEmpty(JSONObject.toJSONString(cmsActivityInfoDto.getLocationList())));
        }

        cmsActivity.setCardReply(cmsActivityInfoDto.getCardReply());
        cmsActivity.setCardTitle(cmsActivityInfoDto.getCardTitle());
        cmsActivity.setCardContent(cmsActivityInfoDto.getCardContent());
        cmsActivity.setCardImg(cmsActivityInfoDto.getCardImg());
        //卡片回复关键字列表
        cmsActivity.setCardKeywords(Tools.getStrEmpty(JSONObject.toJSONString(cmsActivityInfoDto.getCardKeywordList())));

        //保存活动
        cmsActivityMapper.updateByIdSelective(cmsActivity);

        //保存活动明细（展示位置）
        List<CmsActivityDetailInfoDto> cmsActivityDetailInfoDtoList = cmsActivityInfoDto.getCmsActivityDetailInfoDtoList();
        if(cmsActivityDetailInfoDtoList != null && cmsActivityDetailInfoDtoList.size() > 0){
            for (CmsActivityDetailInfoDto cmsActivityDetailInfoDto : cmsActivityDetailInfoDtoList) {
                if(cmsActivityDetailInfoDto.getId() != null){//修改
                    CmsActivityDetail cmsActivityDetail = cmsActivityDetailMapper.selectById(cmsActivityDetailInfoDto.getId(), cmsActivityInfoDto.getMerId());
                    if(cmsActivityDetail != null){
                        cmsActivityDetail.setUpdateTime(now);
                        String value = cmsActivityDetailInfoDto.getValue();
                        if(StringUtils.isNotBlank(value)){
                            JSONObject jsonObjectValue = JSONObject.parseObject(value);
                            jsonObjectValue.put("id", cmsActivityDetail.getId() + "");
                            jsonObjectValue.put("url",cmsActivity.getUrl());
                            jsonObjectValue.put("activityId", cmsActivity.getId() + "");
                            jsonObjectValue.put("startTime", cmsActivity.getStartTime());
                            jsonObjectValue.put("endTime", cmsActivity.getEndTime());
                            cmsActivityDetail.setValue(Tools.getStrEmpty(JSONObject.toJSONString(jsonObjectValue)));
                            cmsActivityDetailMapper.updateByIdSelective(cmsActivityDetail);
                        }
                    }
                }else{  //新增
                    CmsActivityDetail cmsActivityDetail = new CmsActivityDetail();
                    cmsActivityDetail.setId(IdWorker.getId());
                    cmsActivityDetail.setCreateTime(now);
                    cmsActivityDetail.setUpdateTime(now);
                    cmsActivityDetail.setMerId(cmsActivityInfoDto.getMerId());
                    cmsActivityDetail.setActivityId(cmsActivity.getId());
                    cmsActivityDetail.setLocation(cmsActivityDetailInfoDto.getLocation());
                    String value = cmsActivityDetailInfoDto.getValue();
                    if(StringUtils.isNotBlank(value)){
                        JSONObject jsonObjectValue = JSONObject.parseObject(value);
                        jsonObjectValue.put("id", cmsActivityDetail.getId() + "");
                        jsonObjectValue.put("url",cmsActivity.getUrl());
                        jsonObjectValue.put("activityId", cmsActivity.getId() + "");
                        jsonObjectValue.put("startTime", cmsActivity.getStartTime());
                        jsonObjectValue.put("endTime", cmsActivity.getEndTime());
                        cmsActivityDetail.setValue(Tools.getStrEmpty(JSONObject.toJSONString(jsonObjectValue)));
                    }
                    cmsActivityDetailMapper.insert(cmsActivityDetail);
                }
            }
        }

        //是否修改了图片连接和开始结束时间，更新CMS首页和个人中心的配置和缓存
        try{
            //1-先检查CMS首页
            MerBaseConfig merBaseConfig_homePage = merBaseConfigMapper.selectByMerId(cmsActivityInfoDto.getMerId(), MerConfigKeyEnum.CMS_HOMEPAGE_CONFIG.getValue());
            if(merBaseConfig_homePage != null){
                CmsHomePageConfigJson cmsHomePageConfigJson = JSONObject.parseObject(merBaseConfig_homePage.getVal(), CmsHomePageConfigJson.class);
                if(cmsHomePageConfigJson != null){
                    List<CmsHomePageConfigJson.Component> components = cmsHomePageConfigJson.getComponents();
                    if(components != null && components.size() > 0){
                        for (CmsHomePageConfigJson.Component component : components) {
                            //图文轮播、营销导航、优惠头条、八宫格、个人中心图文
                            if(Arrays.asList("PicWord","MarketNavigate","MostOne","PersonalGrid","PersonalPicWord").contains(Tools.getStr(component.getName()))){
                                CmsHomePageConfigJson.Config config = component.getConfig();
                                if(config != null) {
                                    List<CmsHomePageConfigJson.ActivityInfo> activityInfoList =   config.getList();
                                    if(activityInfoList != null && activityInfoList.size() > 0){
                                        for (CmsHomePageConfigJson.ActivityInfo activityInfo : activityInfoList){
                                            if(String.valueOf(cmsActivity.getId()).equals(activityInfo.getActivityId())){
                                                activityInfo.setStartTime(cmsActivity.getStartTime());
                                                activityInfo.setEndTime(cmsActivity.getEndTime());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //保存数据库
                    merBaseConfig_homePage.setVal(JSONObject.toJSONString(cmsHomePageConfigJson));
                    merBaseConfigMapper.update(merBaseConfig_homePage);

                    //保存到redis换成当中
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.CMS_HOMEPAGE_CONFIG.getKey(), merBaseConfig_homePage.getMerId()), merBaseConfig_homePage.getVal());
                }
            }

            //2-在检查个人配置中心
            MerBaseConfig merBaseConfig_personalCenter = merBaseConfigMapper.selectByMerId(cmsActivityInfoDto.getMerId(), MerConfigKeyEnum.CMS_PERSONAL_CENTER_CONFIG.getValue());
            if(merBaseConfig_personalCenter != null){
                CmsHomePageConfigJson cmsHomePageConfigJson = JSONObject.parseObject(merBaseConfig_personalCenter.getVal(), CmsHomePageConfigJson.class);
                if(cmsHomePageConfigJson != null){
                    List<CmsHomePageConfigJson.Component> components = cmsHomePageConfigJson.getComponents();
                    if(components != null && components.size() > 0) {
                        for (CmsHomePageConfigJson.Component component : components) {
                            //图文轮播、营销导航、优惠头条、八宫格、个人中心图文
                            if (Arrays.asList("PicWord", "MarketNavigate", "MostOne", "PersonalGrid", "PersonalPicWord").contains(Tools.getStr(component.getName()))) {
                                CmsHomePageConfigJson.Config config = component.getConfig();
                                if (config != null) {
                                    List<CmsHomePageConfigJson.ActivityInfo> activityInfoList = config.getList();
                                    if (activityInfoList != null && activityInfoList.size() > 0) {
                                        for (CmsHomePageConfigJson.ActivityInfo activityInfo : activityInfoList) {
                                            if (String.valueOf(cmsActivity.getId()).equals(activityInfo.getActivityId())) {
                                                activityInfo.setStartTime(cmsActivity.getStartTime());
                                                activityInfo.setEndTime(cmsActivity.getEndTime());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //保存数据库
                    merBaseConfig_personalCenter.setVal(JSONObject.toJSONString(cmsHomePageConfigJson));
                    merBaseConfigMapper.update(merBaseConfig_personalCenter);
                    //保存到redis换成当中
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.CMS_PERSONAL_CENTER_CONFIG.getKey(), merBaseConfig_personalCenter.getMerId()), merBaseConfig_personalCenter.getVal());

                }
            }
        }catch (Exception e){
            logger.error("json error={}",e.getMessage());
        }


    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param cmsActivityIdListDto
     * @return null
     */
    @Transactional
    public void deleteCmsActivity(CmsActivityIdListDto cmsActivityIdListDto){

        List<Long> idList = cmsActivityIdListDto.getIdList();

        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        for (Long id : idList){
            CmsActivity cmsActivity = cmsActivityMapper.selectById(id, cmsActivityIdListDto.getMerId());
            if(cmsActivity != null){
                //删除活动
                cmsActivityMapper.deleteById(id, cmsActivityIdListDto.getMerId());
                //删除活动位置详情
                cmsActivityDetailMapper.deleteByActivityId(id, cmsActivityIdListDto.getMerId());

                //是否修改了图片连接和开始结束时间，更新CMS首页和个人中心的配置和缓存
                try{
                    //1-先检查CMS首页
                    MerBaseConfig merBaseConfig_homePage = merBaseConfigMapper.selectByMerId(cmsActivityIdListDto.getMerId(), MerConfigKeyEnum.CMS_HOMEPAGE_CONFIG.getValue());
                    if(merBaseConfig_homePage != null){
                        CmsHomePageConfigJson cmsHomePageConfigJson = JSONObject.parseObject(merBaseConfig_homePage.getVal(), CmsHomePageConfigJson.class);
                        if(cmsHomePageConfigJson != null){
                            List<CmsHomePageConfigJson.Component> components = cmsHomePageConfigJson.getComponents();
                            if(components != null && components.size() > 0) {
                                for (CmsHomePageConfigJson.Component component : components) {
                                    //图文轮播、营销导航、优惠头条、八宫格、个人中心图文
                                    if (Arrays.asList("PicWord", "MarketNavigate", "MostOne", "PersonalGrid", "PersonalPicWord").contains(Tools.getStr(component.getName()))) {
                                        CmsHomePageConfigJson.Config config = component.getConfig();
                                        if (config != null) {
                                            List<CmsHomePageConfigJson.ActivityInfo> activityInfoList = config.getList();
                                            if (activityInfoList != null && activityInfoList.size() > 0) {
                                                for (int i = activityInfoList.size() - 1; i >= 0; i--) {
                                                    if (String.valueOf(cmsActivity.getId()).equals(activityInfoList.get(i).getActivityId())) {
                                                        activityInfoList.remove(i);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //保存数据库
                            merBaseConfig_homePage.setVal(JSONObject.toJSONString(cmsHomePageConfigJson));
                            merBaseConfigMapper.update(merBaseConfig_homePage);

                            //保存到redis换成当中
                            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.CMS_HOMEPAGE_CONFIG.getKey(), merBaseConfig_homePage.getMerId()), merBaseConfig_homePage.getVal());
                        }
                    }

                    //2-在检查个人配置中心
                    MerBaseConfig merBaseConfig_personalCenter = merBaseConfigMapper.selectByMerId(cmsActivityIdListDto.getMerId(), MerConfigKeyEnum.CMS_PERSONAL_CENTER_CONFIG.getValue());
                    if(merBaseConfig_personalCenter != null){
                        CmsHomePageConfigJson cmsHomePageConfigJson = JSONObject.parseObject(merBaseConfig_personalCenter.getVal(), CmsHomePageConfigJson.class);
                        if(cmsHomePageConfigJson != null){
                            List<CmsHomePageConfigJson.Component> components = cmsHomePageConfigJson.getComponents();
                            if(components != null && components.size() > 0) {
                                for (CmsHomePageConfigJson.Component component : components) {
                                    //图文轮播、营销导航、优惠头条、八宫格、个人中心图文
                                    if (Arrays.asList("PicWord", "MarketNavigate", "MostOne", "PersonalGrid", "PersonalPicWord").contains(Tools.getStr(component.getName()))) {
                                        CmsHomePageConfigJson.Config config = component.getConfig();
                                        if (config != null) {
                                            List<CmsHomePageConfigJson.ActivityInfo> activityInfoList = config.getList();
                                            if (activityInfoList != null && activityInfoList.size() > 0) {
                                                for (int i = activityInfoList.size() - 1; i >= 0; i--) {
                                                    if (String.valueOf(cmsActivity.getId()).equals(activityInfoList.get(i).getActivityId())) {
                                                        activityInfoList.remove(i);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //保存数据库
                            merBaseConfig_personalCenter.setVal(JSONObject.toJSONString(cmsHomePageConfigJson));
                            merBaseConfigMapper.update(merBaseConfig_personalCenter);
                            //保存到redis换成当中
                            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.CMS_PERSONAL_CENTER_CONFIG.getKey(), merBaseConfig_personalCenter.getMerId()), merBaseConfig_personalCenter.getVal());
                        }
                    }
                }catch (Exception e){
                    logger.error("json error={}",e.getMessage());
                }
            }
        }
    }

    /**
     * 分页查询CMS活动展示位置信息列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return CmsActivityInfoVo
     */
    public Page<CmsActivityDetailInfoVo> findCmsActivityDetailList(CmsActivityDetailQuery cmsActivityDetailQuery) {
        //新建返回到页面的LIST对象
        List<CmsActivityDetailInfoVo> cmsActivityInfoVoArrayList = new ArrayList<>();
        //返回到页面分页对象
        Page<CmsActivityDetailInfoVo> pageVo = new Page<>();

        //执行分页查询对象
        Page<CmsActivityDetail> page = new Page<>();
        cmsActivityDetailQuery.convert(page);
        List<CmsActivityDetail> cmsActivityDetailList = cmsActivityDetailMapper.findByList(page, cmsActivityDetailQuery);
        if (cmsActivityDetailList != null) {
            for (CmsActivityDetail cmsActivityDetail : cmsActivityDetailList) {
                CmsActivityDetailInfoVo cmsActivityDetailInfoVo = new CmsActivityDetailInfoVo();
                BeanUtils.copyProperties(cmsActivityDetail, cmsActivityDetailInfoVo);
                cmsActivityInfoVoArrayList.add(cmsActivityDetailInfoVo);
            }
        }
        BeanUtils.copyProperties(page, pageVo);
         pageVo.setRecords(cmsActivityInfoVoArrayList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }


    /**
     * 修改CMS活动展示位置配置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param cmsActivityDetailInfoDto
     * @return null
     */
    @Transactional
    public void updateCmsActivityDetail(CmsActivityDetailInfoDto cmsActivityDetailInfoDto){

        if(cmsActivityDetailInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        if(StringUtils.isBlank(cmsActivityDetailInfoDto.getValue())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动配置内容");
        }

        CmsActivityDetail cmsActivityDetail = cmsActivityDetailMapper.selectById(cmsActivityDetailInfoDto.getId(), cmsActivityDetailInfoDto.getMerId());

        if(cmsActivityDetail == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该活动展示位置配置信息不存在");
        }

        Integer now = DateUtil.getNowTime();
        cmsActivityDetail.setUpdateTime(now);
        cmsActivityDetail.setValue(cmsActivityDetailInfoDto.getValue());

        //保存活动展示位置
        cmsActivityDetailMapper.updateByIdSelective(cmsActivityDetail);
    }

    /**
     * 分页查询活动关联的商品详情信息列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return CmsActivityInfoVo
     */
    public Page<CmsTbGoodsInfoVo> findCmsActivityGoodsInfoList(CmsActivityDetailQuery cmsActivityDetailQuery) {

        //新建返回到页面的LIST对象
        List<CmsTbGoodsInfoVo> cmsTbGoodsInfoVoList = new ArrayList<>();
        //返回到页面分页对象
        Page<CmsTbGoodsInfoVo> page = new Page<>();
        cmsActivityDetailQuery.convert(page);

        if(cmsActivityDetailQuery.getActivityId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动id");
        }

        CmsActivity cmsActivity = cmsActivityMapper.selectById(cmsActivityDetailQuery.getActivityId(), cmsActivityDetailQuery.getMerId());
        if(cmsActivity == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该活动不存在");
        }

        List<String> itemIdList = JSONObject.parseArray(cmsActivity.getItemId(), String.class);

        if(itemIdList != null){
            //开始下标
            int startIndex = cmsActivityDetailQuery.getSize() * (cmsActivityDetailQuery.getCurrent()-1);
            //结束下标
            int endIndex = cmsActivityDetailQuery.getSize() * cmsActivityDetailQuery.getCurrent();
            //判断结束下标是否大于列表的长度，如果大于，则取列表的长度作为结束
            if(endIndex > itemIdList.size()){
                endIndex = itemIdList.size();
            }

            for (int i = startIndex; i < endIndex; i++){
                //商品id
                String itemId = itemIdList.get(i);

                //调用CMS接口，查询该商品的信息
                CmsTbGoodsQuery cmsTbGoodsQuery = new CmsTbGoodsQuery();
                cmsTbGoodsQuery.setKeyword(itemId+"");
                cmsTbGoodsQuery.setMerId(cmsActivityDetailQuery.getMerId());
                cmsTbGoodsQuery.setBack(1);
                cmsTbGoodsQuery.setMinId("1");
                CmsTbGoodsInfoVo cmsTbGoodsInfoVo = cmsTbGoodsService.findCmsTbGoodsInfo(cmsTbGoodsQuery);
                if(cmsTbGoodsInfoVo != null){
                    cmsTbGoodsInfoVoList.add(cmsTbGoodsInfoVo);
                }
//
//                CmsMerTbGoods cmsMerTbGoods = cmsMerTbGoodsMapper.selectByMerIdAndItemid(cmsActivityDetailQuery.getMerId(), itemId);
//                if(cmsMerTbGoods != null){
//                    CmsTbGoodsInfoVo cmsTbGoodsInfoVo = new CmsTbGoodsInfoVo();
//                    BeanUtils.copyProperties(cmsMerTbGoods, cmsTbGoodsInfoVo);
//                    cmsTbGoodsInfoVoList.add(cmsTbGoodsInfoVo);
//                }
            }
        }
        page.setRecords(cmsTbGoodsInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }


}
